import { ListNode } from "./ListNode"

/**
 * 2. 两数相加
 * @param l1 链表1
 * @param l2 链表2
 * @returns ListNode | null
 */
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
  // 新建空链表
  const l3 = new ListNode(0)
  let p1 = l1
  let p2 = l2
  let p3 = l3
  let carry = 0
  while (p1 || p2) {
    const v1 = p1 ? p1.val : 0
    const v2 = p2 ? p2.val : 0
    const val = v1 + v2 + carry
    carry = Math.floor(val / 10)
    p3.next = new ListNode(val % 10)
    if (p1) p1 = p1.next
    if (p2) p2 = p2.next
    p3 = p3.next
  }
  // 如果个位数相加进1,则额外相加
  if (carry) {
    p3.next = new ListNode(carry)
  }
  return l3.next
}